package br.jm.i18n;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class ResourceBundleMessageProvider implements MessageProvider {

	final ResourceBundle rb;

	public ResourceBundleMessageProvider(final Path classFilePath, final Locale loc) throws IOException {
		final String name = MessageFormat.format("{0}_{1}.properties", classFilePath.getFileName().toString().replace(".class", ""), loc.toString());
		final Path path = classFilePath.resolveSibling(name);

		try (InputStream is = Files.newInputStream(path)) {
			rb = new PropertyResourceBundle(is);
		}
	}

	@Override
	public String getMessage(final String key, final Locale loc, final Object... args) {
		try {
			final String val = rb.getString(key);
			return args.length > 0 ? MessageFormat.format(val, args) : val;
		} catch (final MissingResourceException ex) {
			return MessageFormat.format("Requires bundle/key for {0} in scope {1}", key, loc);
		}
	}
}
